package study.springboot.starter.tacker.filter;

import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;
import study.springboot.starter.tacker.Headers;
import study.springboot.starter.tacker.TrackerKeys;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class TrackerFilter extends OncePerRequestFilter {

    private static final String X_REQUEST_ID = "request_id";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //获取request id
        String requestId = request.getHeader(Headers.X_REQUEST_ID);
        String uri = request.getRequestURI();
        if (Strings.isNullOrEmpty(requestId)) {
            log.warn("uri {} request id is null or empty", uri);
        }
        //打印request id
        MDC.put(X_REQUEST_ID, requestId);
        //传递request id
        TrackerKeys.set(requestId);
        try {
            doFilter(request, response, filterChain);
        } finally {
            TrackerKeys.remove();
            MDC.remove(X_REQUEST_ID);
        }
    }
}
